package com.hn658.groupshare.common.log.dao.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import com.hn658.framework.dataaccess.mongo.AbstractMongoDBDaoImpl;
import com.hn658.groupshare.common.log.dao.ILogMongoDBDAO;
import com.hn658.groupshare.common.log.entity.LogInfo;

/**
 * 日志DB实现
 * @author ztjie
 *
 */
@Repository
public class LogMongoDBDAOImpl extends AbstractMongoDBDaoImpl<LogInfo> implements ILogMongoDBDAO{

	@Override
	public List<LogInfo> findByQueryMap(Query query,
			int limit, int start) {
		if (query == null || limit < 0 || start < 0) {
			return null;
		}
		query.with(new Sort(Sort.Direction.DESC, "createTime"));
		query.skip(start);
		if (limit > 0) {
			query.limit(limit);
		}
		return this.mongoTemplate.find(query, clazz);
	}
	
	@Override
	public Query getQuery(Map<String, Object> queryMap){
		Query query = new Query();
		Criteria criteria = new Criteria();
		if(queryMap.get("operateInfo")!=null){
			criteria.and("operateInfo").regex(queryMap.get("operateInfo").toString());	
			queryMap.remove("operateInfo");
		}
		if(queryMap.get("createStartTime")!=null||queryMap.get("createEndTime")!=null){
			Criteria criteriaTime = Criteria.where("createTime");
			if(queryMap.get("createStartTime")!=null){
				Date createStartTime = (Date)queryMap.get("createStartTime");
				criteriaTime.gte(createStartTime.getTime());
				queryMap.remove("createStartTime");
			}
			if(queryMap.get("createEndTime")!=null){
				Date createEndTime = (Date)queryMap.get("createEndTime");
				criteriaTime.lte(createEndTime.getTime());
				queryMap.remove("createEndTime");
			}
			query.addCriteria(criteriaTime);
		}
		for (String key : queryMap.keySet()) {
			Object value = queryMap.get(key);
			if (value != null) {
				criteria.and(key).is(value);
			}
		}
		query.addCriteria(criteria);
		return query;
	}

}
